extends Node

var loocker_api_key: String = ""
var loocker_is_dev: bool = true
var loocker_player_id_path: String = "user://LootLocker.data"
var loocker_game_version: String = "0.0.1"
var loocker_api_url: String = ""
var loocker_domain_key: String = ""

var loocker_should_save_login: bool = true

var session_token: String = ""
var session_online: bool = false

func start_guest_session():
	var player_session_exists = false
	var player_identifier : String

	# Check if player has previously registered as guest
	var file = File.new()
	file.open(loocker_player_id_path, file.READ)
	if file != null:
		player_identifier = file.get_as_text()
		file.close()
	if player_identifier != null and player_identifier.length() > 1:
		player_session_exists = true
	if(player_identifier.length() > 1):
		player_session_exists = true
	var data = { "game_key": loocker_api_key, "game_version": "0.0.0.1", "development_mode": loocker_is_dev }

	if(player_session_exists == true):
		data = { "game_key": loocker_api_key, "player_identifier":player_identifier, "game_version": loocker_game_version, "development_mode": loocker_is_dev }
	var headers = ["Content-Type: application/json"]
	var auth_http = HTTPRequest.new()
	add_child(auth_http)
	auth_http.request(loocker_api_url + "game/v2/session/guest", headers, true, HTTPClient.METHOD_POST, to_json(data))
	var response = yield(auth_http, "request_completed")
	response = JSON.parse(response[3].get_string_from_utf8()).result
	
	if !response.success:
		return response
	
	if loocker_should_save_login:
		file.open(loocker_player_id_path, file.WRITE)
		file.store_string(response.player_identifier)
		file.close()
	
	session_token = response.session_token
	session_online = true
	auth_http.queue_free()
	return response

func get_messages():
	var message_http = HTTPRequest.new()
	add_child(message_http)
	var headers: Array = ["x-session-token: " + String(session_token)]
	message_http.request(loocker_api_url + "game/v1/messages", headers, true, HTTPClient.METHOD_GET)
	var response = yield(message_http, "request_completed")
	response = JSON.parse(response[3].get_string_from_utf8()).result
	message_http.queue_free()
	return response

func end_session():
	var end_http = HTTPRequest.new()
	add_child(end_http)
	var headers = ["x-session-token: " + String(session_token)]
	end_http.request(loocker_api_url + "game/v1/session/end", headers, true, HTTPClient.METHOD_POST)
	var response = yield(end_http, "request_completed")
	response = JSON.parse(response[3].get_string_from_utf8()).result
	return response

